package com.xana.mkplayer;

import androidx.appcompat.app.AppCompatActivity;

import android.content.res.Configuration;
import android.os.Bundle;
import android.util.Log;
import android.view.SurfaceView;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

    String url = "https://1251316161.vod2.myqcloud.com/007a649dvodcq1251316161/8c3785775285890808198017973/g33AvJvA1mEA.mp4";
    String uri = "https://sf1-ttcdn-tos.pstatp.com/obj/tos-cn-v-0004/e1256e9a78644b3ea14104ebdc430792?partNumber";
    String live = "rtmp://112.74.191.65/myapp/mystream";
    MKPlayer mkPlayer = null;

    boolean init = true;
    SurfaceView surfaceView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        surfaceView = findViewById(R.id.surfaceView);
        mkPlayer = new MKPlayer();
    }

    @Override
    protected void onResume() {
        initWidgt();
        super.onResume();
    }

    private void initWidgt() {
        if(!init)
            return;
        init = false;

        mkPlayer.setSurfaceView(surfaceView);
        mkPlayer.setDataSource(uri);

        mkPlayer.prepare();
        mkPlayer.setOnPrepareListener(new MKPlayer.OnPrepareListener() {
            @Override
            public void onPrepared(final MKPlayer mp) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        ViewGroup.LayoutParams layoutParams = surfaceView.getLayoutParams();
                        layoutParams.height = surfaceView.getMeasuredWidth()*mp.mHeight/mp.mWidth;
                        surfaceView.setLayoutParams(layoutParams);
                        mp.start();
                    }
                });
            }
        });
    }
    public void stop(View view) {

    }


    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
            getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager
                    .LayoutParams.FLAG_FULLSCREEN);
        } else {
            getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
        }
        setContentView(R.layout.activity_play);
        surfaceView = findViewById(R.id.surfaceView);
        mkPlayer.setSurfaceView(surfaceView);
        mkPlayer.setDataSource(url);
    }

    @Override
    protected void onStop() {
        if(mkPlayer!=null)
            mkPlayer.stop();
        super.onStop();
    }
}
